package DAO;

import util.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：hzs
 * @date ：Created in 2021/1/2 15:43
 * @description：
 * @modified By：
 * @version: $
 */
public class BaseDAO {



    /**
     * 执行写操作的SQL语句
     */
    public boolean executeWriteSql(String sql) {
        try(Connection connection = JDBCUtil.getConnection()) {
            try (Statement statement = connection.createStatement()) {
                int execute = statement.executeUpdate(sql);
                return execute > 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 执行读操作的SQL语句
     */
    public List<List<Object>> executeReadSql(String sql) {
        try(Connection connection = JDBCUtil.getConnection()) {
            try (Statement statement = connection.createStatement()) {
                ResultSet resultSet1 = statement.executeQuery(sql);
                List<List<Object>> result = new ArrayList<>();
                while (resultSet1.next()) {
                    int columnCount = resultSet1.getMetaData().getColumnCount();
                    List<Object> line = new ArrayList<>();
                    for (int i = 1; i <= columnCount; i++) {
                        line.add(resultSet1.getObject(i));
                    }
                    result.add(line);
                }
                return result;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
